﻿using MyFramework.Resource;
using MyFramework.Singleton;
using UnityEngine;

namespace MyFramework.MVCLibrary
{
    // ReSharper disable once ClassNeverInstantiated.Global
    public class UIRoot : Singleton<UIRoot>
    {
        private static Transform _uiRootTransform;

        /// <summary>
        /// 关闭的或暂时不显示的view（可放入对象池）
        /// </summary>
        private Transform _recyclePool;

        /// <summary>
        /// 当前显示的view
        /// </summary>
        private Transform _workStation;

        /// <summary>
        /// 提示弹窗
        /// </summary>
        private Transform _noticeStation;

        private bool _isInit = false;

        /// <summary>
        /// UIRoot初始化
        /// </summary>
        private void Init()
        {
            if (!_uiRootTransform)
            {
                // GameObject obj = Resources.Load<GameObject>("UI/UIRoot"); // 从Resources下加载
                GameObject obj = AssetBundleManager.GetInstance().LoadGameObject("ui", "UIRoot"); // 从AssetBundle中加载
                _uiRootTransform = obj.transform;
            }

            if (!_recyclePool)
            {
                _recyclePool = FindTemplate("recyclePool");
            }

            if (!_workStation)
            {
                _workStation = FindTemplate("workStation");
            }

            _isInit = true;
        }

        /// <summary>
        /// 重构：模板方法
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private Transform FindTemplate(string name)
        {
            return _uiRootTransform.Find(name);
        }

        public void SetParent(Transform view, bool isOpen, bool isNotice = false)
        {
            if (_isInit == false)
            {
                Init();
            }

            if (isOpen)
            {
                view.SetParent(isNotice ? _noticeStation : _workStation, false);
            }
            else
            {
                view.SetParent(_recyclePool, false);
            }
        }
    }
}